import select
import socket

# Create a TCP/IP socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)

# Bind the socket to the port
server_address = ('localhost', 8888)
server.bind(server_address)

if 1:
    from shells.sshKillOldProcessing import run as kill_old_processing
    kill_old_processing(port=server_address[-1])

print(f'--- 正在监听 {server_address}')

# Listen for incoming connections
server.listen(5)

# Keep track of the clients that are connected
inputs = [server]

while inputs:
    # Wait for at least one of the sockets to be ready for processing
    readable, writable, exceptional = select.select(inputs, [], inputs)

    # Handle inputs
    for s in readable:
        if s is server:
            # A new connection request received
            client, client_address = s.accept()
            client.setblocking(0)
            inputs.append(client)
        else:
            # Data received from a client
            data = s.recv(1024)
            if data:
                # Send the data back to the client
                s.send(data)
            else:
                # No more data, close the connection
                s.close()
                inputs.remove(s)

    # Handle exceptions
    for s in exceptional:
        inputs.remove(s)
        s.close()
